from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from xml.dom.minidom import parse, parseString

from models.project import MasterControlProject

import logging
from settings import *
from utilities import *

class MasterProjectActivityHookHandler(webapp.RequestHandler):
    def post(self, mcp_code):
        mcp = MasterControlProject.get_by_key_name(mcp_code)
        if not mcp:
            return
        
        activity_document = parseString(self.request.body)
        event_type = activity_document.getElementsByTagName('event_type')[0].firstChild.data
        if event_type not in ['story_update', 'note_create']:
            return
        
        for story in activity_document.getElementsByTagName('story'):
            story_id = story.getElementsByTagName('id')[0].firstChild.data.strip()
            complete_story = GetStory(mcp.pivotal_project_id, story_id, mcp.token)
            labels = complete_story.getElementsByTagName('labels')
            if not labels or not labels[0].firstChild:
                continue
            labels = labels[0].firstChild.data.split(',')
            subproject = mcp.subprojects.filter('label in', labels).get()
            if not subproject:
                subproject = mcp.subprojects.filter('old_lables in', labels).get()
                if not subproject:
                    continue
            
            external_story = GetStories(subproject.pivotal_project_id, subproject.token or mcp.token, 'external_id:' + story_id)
            if not external_story:
                continue
            external_story = external_story.getElementsByTagName('story')
            if not external_story:
                continue
            external_story = external_story[0]
            external_id = filter(lambda n: hasattr(n, 'tagName') and n.tagName == 'id', external_story.childNodes)[0].firstChild.data
            
            if event_type == 'story_update':
                RemoveTags(story, 'id', 'other_id', 'url', 'other_url', 'integration_id', 'owned_by', 'requested_by', 'created_at')
                labels = story.getElementsByTagName('labels')
                if labels:
                    labels = labels[0]
                    tags = labels.firstChild.data.split(',')
                    for label in [subproject.label] + subproject.old_labels:
                        if label in tags:
                            tags.remove(label)
                    tags = sorted(tags)
                    labels.firstChild.data = ",".join(tags)
                state = story.getElementsByTagName('current_state')
                if state:
                    state = state[0].firstChild.data.strip()
                    if state not in ['accepted', 'rejected']:
                        RemoveTags(story, 'current_state')
                UpdateStory(subproject.pivotal_project_id, external_id, subproject.token or mcp.token, story)
            elif event_type == 'note_create':
                content = activity_document.getElementsByTagName('note')[0]
                content = content.getElementsByTagName('text')[0].firstChild.data.strip()
                author = activity_document.getElementsByTagName('author')[0].firstChild.data.strip()
                comment = '%s said: %s' % (author, content)
                AddComment(subproject.pivotal_project_id, external_id, subproject.token or mcp.token, comment)
            try:
                if mcp.activities_processed:
                    mcp.activities_processed += 1
                else:
                    mcp.activities_processed = 1
                mcp.put()
            except:
                pass